using UnityEngine;
using System.Collections;

[System.Serializable]
public class PositionData
{
    public int frame;
    public float forward;
    public float up;
    public float right;
}

//change speed according
[System.Serializable]
public class PositionByValueGroupOnUpdate : CharacterAction
{
    public int dataLength = 1;
    public PositionData[] positionGroup;

    protected float forwardSpeed;
    protected float upSpeed;
    protected float rightdSpeed;
   
    private Vector3 speed;
    private int nextFrame = 1000;
    private int index = 0;

    public override void OnActionEnter(Character character)
    {
        base.OnActionEnter(character);
        index = 0;

        if(positionGroup.Length > 0)
        {
            nextFrame = positionGroup[0].frame;
            CalculateSpeed(0);
            index += 1;
        }
    }

    public override void OnActionExit(Character character)
    {
        speed = Vector3.zero;//reset speed
        base.OnActionExit(character);
    }

    public override void OnFrameUpdate (Character.FrameUpdate arg)
    {
        Character character = arg.character;
        if(character.curFrame > nextFrame)//change to new speed
        {
            if(index == positionGroup.Length)
            {
                return;
            }
            else{
                nextFrame = positionGroup[index].frame;
                CalculateSpeed(index);
                index += 1;
            }
        }
        else
        {
            UpdateSpeed( );//only if character transform being changed
            character.rigidbodyRef.velocity = speed;
        }
    }

    void CalculateSpeed(int index)
    {
        float deltaTime = 0;
        if(index == 0)
        {
            deltaTime = positionGroup[index].frame * character.curState.duration/character.curState.frames;
        }
        else
        {
            deltaTime = ( positionGroup[index].frame - positionGroup[index-1].frame )* character.curState.duration/character.curState.frames;
        }

        forwardSpeed = positionGroup[index].forward/deltaTime;
        upSpeed = positionGroup[index].up/deltaTime;
        rightdSpeed = positionGroup[index].right/deltaTime;

        UpdateSpeed( );
    }

    void UpdateSpeed( )
    {
        Vector3 velocityZ = character.transformRef.forward;
        Vector3 velocityY = character.transformRef.up;
        Vector3 velocityX = character.transformRef.right;
        
        velocityZ *= forwardSpeed;
        velocityY *= upSpeed;
        velocityX *= rightdSpeed;
        
        speed = velocityZ + velocityY + velocityX;
    }
}

